<?php

namespace app\model;

use think\Model;
use think\model\relation\BelongsTo;

class WithdrawOrderRecords extends Model
{
    // 设置当前模型对应的数据表
    protected $name = 'withdraw_order_records';
    // 设置当前模型主键
    protected $pk = 'id';

    protected $autoWriteTimestamp = 'datetime';
    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    //提现状态
    const STATUS_PENDING = 'pending';//申请中
    const STATUS_FAIL = 'fail';//申请失败
    const STATUS_APPLY_SUCCESS = 'apply_success';//申请成功
    const STATUS_DONE = 'done';//提现成功
    const STATUS_ARR = [
        self::STATUS_PENDING => '申请中',
        self::STATUS_FAIL => '申请失败',
        self::STATUS_APPLY_SUCCESS => '申请成功',
        self::STATUS_DONE => '提现成功',
    ];

    // 添加/修改数据
    public function edit($params)
    {
        if (empty($params['id'])) {
            $data = $this::create($params);
            return $data->id;
        }
        $this::update($params);
        return $params['id'];
    }

    // 根据id获取数据
    public function getInfoById($id, $fields = 'id, name')
    {
        $data = $this::where(['id' => $id])->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    // 获取分页数据
    public function getPagingDataByWhere($where = [], $page = 1, $limit = 10, $fields = 'id, name', $order = 'id desc')
    {
        $total = $this::where($where)->count();

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $totalPage = ceil($total / $limit);
        $offset = ($page - 1) * $limit;

        $data = $this::where($where)->field($fields)->order($order)->limit($offset, $limit)->select();

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    // 获取所有数据
    public function getDataByWhere($where = [], $fields = 'id, name', $order = 'id asc')
    {
        $data = $this::where($where)->field($fields)->order($order)->select();
        return $data ? $data->toArray() : [];
    }

    // 根据条件获取一条数据
    public function getInfoByWhere(array $where, $fields = 'id, name')
    {
        $data = $this::where($where)->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 关联小程序model
     * @return BelongsTo
     */
    public function applet(): BelongsTo
    {
        return $this->belongsTo('app\model\Applet', 'applet_id', 'id');
    }

    /**
     * 关联操作人员model
     * @return BelongsTo
     */
    public function admin(): BelongsTo
    {
        return $this->belongsTo('app\model\Admin', 'operator_id', 'id');
    }
}